package com.ruoyi.logistic.service.impl;

import com.ruoyi.logistic.domain.NetworkOutboundSettlement;
import com.ruoyi.logistic.service.FileService;
import com.ruoyi.logistic.service.INetworkOutboundSettlementService;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpStatus;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private INetworkOutboundSettlementService networkOutboundSettlementService;
    @Value("${file.path}")
    private String realPath;
    @Deprecated
    public ResponseEntity<byte[]> download(String fileName) {
        try {

            //创建该图片的对象
            File file = new File(realPath+fileName);
            //将图片数据读取到字节数组中
            byte[] bytes = FileUtils.readFileToByteArray(file);
            //创建 HttpHeaders 对象设置响应头信息
            HttpHeaders httpHeaders = new HttpHeaders();
            //设置图片下载的方式和文件名称
            httpHeaders.setContentDispositionFormData("attachment", toUTF8String(fileName));
            httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.SC_OK);

        }catch (Exception e){
            e.printStackTrace();
        }
        return null;

    }

    @Override
    public ResponseEntity<byte[]> downloadNetworkOutboundSettlement(Integer[] ids, HttpServletResponse response) {
        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet("出港结算关系配置表");
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("序号");
        headerRow.createCell(1).setCellValue("结算主体名称");
        headerRow.createCell(2).setCellValue("结算主体编号");
        headerRow.createCell(3).setCellValue("结算主体类型");
        headerRow.createCell(4).setCellValue("结算对象名称");
        headerRow.createCell(5).setCellValue("结算对象编号");
        headerRow.createCell(6).setCellValue("结算对象类型");
        headerRow.createCell(7).setCellValue("结算哪些客户的包裹");
        headerRow.createCell(8).setCellValue("已选报价类型");
        headerRow.createCell(9).setCellValue("是否个性化计泡");
        headerRow.createCell(10).setCellValue("个性化计泡参数");
        headerRow.createCell(11).setCellValue("创建时间");
        if (ids != null && ids.length > 0) {
            List<NetworkOutboundSettlement> settlements = networkOutboundSettlementService.findByIds(ids);
            for (int i = 0; i < settlements.size(); i++) {
                Row row = sheet.createRow(i + 1);
                NetworkOutboundSettlement settlement = settlements.get(i);
                if (settlement == null) {
                    continue;
                }
                row.createCell(0).setCellValue(settlement.getId());
                row.createCell(1).setCellValue(settlement.getNetworkName());
                row.createCell(2).setCellValue(settlement.getSiteCode());
                row.createCell(3).setCellValue(settlement.getTypeName());
                row.createCell(4).setCellValue(settlement.getClientId());
                row.createCell(5).setCellValue(settlement.getObjectCode());
                row.createCell(6).setCellValue(settlement.getObjectType());
                row.createCell(7).setCellValue(settlement.getCustomerPackageType());
//                row.createCell(8).setCellValue(settlement.getQuotation().getQuotationType().getTitle());
                row.createCell(9).setCellValue(settlement.getIsBubble());
                row.createCell(10).setCellValue(settlement.getBubbleParameter());
                row.createCell(11).setCellValue(settlement.getCreateTime());
            }
        }
        try {
            LocalDate localDate = LocalDate.now();
            String fileName = "出港结算关系配置表" + localDate.getYear() + "年" + localDate.getMonthValue() + "月" + localDate.getDayOfMonth() + "日";
            //生成一张表
            response.setHeader("Content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "form-data; name=\"attachment\"; filename=\"" + URLEncoder.encode("出港结算关系配置表", "UTF-8") + ".xls");
            workbook.write(response.getOutputStream());
            return new ResponseEntity<>(org.springframework.http.HttpStatus.OK);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 下载保存时中文文件名的字符编码转换方法
     */
    public String toUTF8String(String str) {
        StringBuffer sb = new StringBuffer();
        int len = str.length();
        for (int i = 0; i < len; i++) {
            // 取出字符中的每个字符
            char c = str.charAt(i);
            // Unicode码值为0~255时，不做处理
            if (c >= 0 && c <= 255) {
                sb.append(c);
            } else { // 转换 UTF-8 编码
                byte b[];
                try {
                    b = Character.toString(c).getBytes("UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    b = null;
                }
                // 转换为%HH的字符串形式
                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0) {
                        k &= 255;
                    }
                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return sb.toString();
    }
}
